package others;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import tool.DataFileHandler;

import model.ConfigElem;
import model.ConfigModel;
import model.Float3D;

public class CloudGen {

	private static final int width = 500;
	private static final int height = 400;
	private static final int radius2 = 10;	// twice of radius

	public static void main(String[] args) {
		if(args.length < 2) {
			System.out.println("Please enter a configuration file name");
			return;
		}
		
		try {
			ConfigModel model = DataFileHandler.parseDataFile(args[1]);

			BufferedImage bi = null;
			Graphics2D g = null;
			File file = null;
			File dir = new File("jpg");
			dir.mkdirs();

			float minX, maxX;
			float minY, maxY;
			float scaleX, scaleY;
			Float3D tempCG;
			List<ConfigElem> list = null;
			for (int i = 0; i <= 40; i++) {
				for (int j = 0; j <= 40; j++) {
					minX = 999999;
					maxX = -999999;
					minY = 999999;
					maxY = -999999;

					list = model.getElemList(i, j);
					for (ConfigElem ce : list) {
						minX = (minX < ce.getCG().x)? minX: ce.getCG().x;
						maxX = (maxX > ce.getCG().x)? maxX: ce.getCG().x;
						minY = (minY < ce.getCG().y)? minY: ce.getCG().y;
						maxY = (maxY > ce.getCG().y)? maxY: ce.getCG().y;
					}
					scaleX = (width - radius2)/(maxX - minX);
					scaleY = (height - radius2)/(maxY - minY);

					// prepare drawing
					bi = new BufferedImage(width, height,
							BufferedImage.TYPE_INT_RGB);
					g = bi.createGraphics();

					// set background:
					g.setBackground(Color.GRAY);
					g.clearRect(0, 0, width, height);

					// set fore color:
					g.setColor(Color.RED);
					
					// start drawing
					for (ConfigElem ce : list) {
						tempCG = ce.getCG();
						g.drawOval((int)((tempCG.x - minX)*scaleX), (int)((tempCG.y - minY)*scaleY), radius2, radius2);
					}

					// finish drawing
					g.dispose();
					bi.flush();

					// encode:					
					file = new File(dir, i + "x" + j + ".jpg");
					file.createNewFile();

					JPEGImageEncoder encoder = JPEGCodec
							.createJPEGEncoder(new FileOutputStream(file));
					JPEGEncodeParam param = encoder
							.getDefaultJPEGEncodeParam(bi);
					param.setQuality(1.0f, false);
					encoder.setJPEGEncodeParam(param);
					encoder.encode(bi);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
